/**
 * @file index.js
 * @author swan
 */
const app = getApp()
var timer = null
var Api = require('../../utils/api.js');
var util = require('../../utils/util.js');
var bdApi = require('../../utils/bdApi.js');
var bdRequest = require('../../utils/bdRequest.js')
import config from '../../utils/config.js'
var pageCount = config.getPageCount;
var WxParse = require('../../wxParse/wxParse.js');
import seoConfig from '../../seoConfig/config.js'
import peoples from '../../utils/peoples.js'
Page({
    data: {
        userInfo: {},
        hasUserInfo: false,
        name:'',
        formType:0, 
        moveDistance:65,
        peoples:150,
        scrollList: peoples,
        copyList:[],
        index:0,
        listLenght:0,
        animStyle: {
            transition: 'all 0.5s',
            'margin-top': 0
        },
        schoolList: ['武汉大学', '肇庆学院', '黄山学院', '贵州轻工', '四川音乐学院', '郑州航空工业', '湖北第二师范学院', '泉州市华光职业技术学院', '上饶市艺术学校'],
        height:'300rpx',
        pickList:['报到证补办','报到证改派','报到证遗失证明','报到证登报']
    },
    selectorChange(e){
  
    },
    onLoad: function (options) {
         let list = this.data.scrollList

        for (let item of list) {
            let num = util.randomNum(0, 8)
            let myphone = item.mobile.substr(3, 4)
            let myname = item.name.substr(0, 1)
            item.name = item.name.length <= 1 ? myname : item.name.length === 2 ? myname + '*' : myname + "**";
            item.school = this.data.schoolList[num]
            item.mobile = item.mobile.replace(myphone, "****");
            item.time = new Date().getFullYear() + '-' + Number(new Date().getMonth() + 1)
        }
        this.setData({
            scrollList: list
        })
        this.setData({
            listLenght: this.data.scrollList.length,
            copyList: this.data.scrollList,
            index: 0
        })
        timer = setInterval(() => {
            this.scroll();
        }, 2000)
        this.setConfig(seoConfig.dabbConfig)  
    },
    onUnload() {
        clearInterval(timer)
        timer = null
    },
    //获得文章分类
    setConfig(seo) {
        swan.setPageInfo && swan.setPageInfo(seo)
    },
    formSubmit: function (e) {
        console.log('form发生了submit事件，携带数据为：', e.detail.value);
        let data = e.detail.value
        if (!data.name || !data.tel || !data.education) {
            swan.showToast({
                title: '请填写所有必填项',
                duration: 1000,
            });
        }
        var url = Api.postFormUrl();
        var ip = new Date().getTime() + Math.round(Math.random() * 10000); // 小程序端无法获取ip
        var content = `类&nbsp;&nbsp;型：档案补办\n姓&nbsp;&nbsp;名：${data.name}\n联系电话：${data.tel}\n学历：${data.education}\n来源： 办得爽百度小程序`
        var postLikeRequest = bdRequest.postRequest(url, { title: "办得爽小程序-档案补办", tel: data.tel, name: data.name, content: content, "from": '百度小程序', ip: ip });
        postLikeRequest
            .then(response => {
                if (response.data.status == '200') {
                    swan.showToast({
                        icon: 'success',
                        title: '提交成功'
                    });
                    this.setData({
                        name: ''
                    })

                }
            })
    },
    getUserInfo(e) {
        swan.login({
            success: () => {
                swan.getUserInfo({
                    success: (res) => {
                        this.setData({
                            userInfo: res.userInfo,
                            hasUserInfo: true
                        });
                    },
                    fail: () => {
                        this.setData({
                            userInfo: e.detail.userInfo,
                            hasUserInfo: true
                        });
                    }
                });
            },
            fail: () => {
                swan.showModal({
                    title: '未登录',
                    showCancel: false
                });
            }
        });
    },
    playPhone() {
        swan.makePhoneCall({
            phoneNumber: '4009687088' //仅为示例，并非真实的电话号码
        });
    },
    //获取文章列表数据
    fetchPostsData: function (data) {
        var self = this;
        if (!data) data = {};
        if (!data.page) data.page = 1;
        if (!data.categories) data.categories = 0;
        if (!data.search) data.search = '';
        if (data.page === 1) {
            self.setData({
                postsList: []
            });
        };
        swan.showLoading({
            title: '正在加载',
            mask: true
        });
        if (data.categories === 0) {
            var getPostsRequest = bdRequest.getRequest(Api.getPosts(data));
        } else {
            var getPostsRequest = bdRequest.getRequest(Api.getPostsByIDs(data));
        }
        getPostsRequest
            .then(response => {
                if (response.statusCode === 200) {
                    for (var i = 0; i < response.data.length; i++) {
                        // console.log(response.data[i].excerpt.rendered);
                        var rendered = response.data[i].excerpt.rendered;
                        if (rendered === '') {
                            continue
                        }
                        var res = WxParse.bdParse('rendered', 'html', rendered, self, 5, true);
                        // console.log(res);
                        response.data[i].excerpt.rendered = res;
                    }
                    if (response.data.length < pageCount) {
                        self.setData({
                            isLastPage: true
                        });
                    } else {
                        self.setData({
                            isLastPage: false
                        });
                    }
                    self.setData({
                        floatDisplay: "block",
                        postsList: self.data.postsList.concat(response.data.map(function (item) {
                            var strdate = item.date
                            if (item.category_name != null) {
                                item.categoryImage = "";
                            }
                            else {
                                item.categoryImage = "";
                            }
                            if (item.post_thumbnail_image == null || item.post_thumbnail_image == '') {
                                item.post_thumbnail_image = "https://www.bds110.com/wp-content/uploads/bdsmp-dacx/logo700.png";
                            }
                            item.date = util.cutstr(strdate, 10, 1);
                            // console.log(item);
                            return item;
                        })),
                    });
                    setTimeout(function () {
                        swan.hideLoading();
                    }, 900);
                }
                else {
                    if (response.data.code == "rest_post_invalid_page_number") {
                        self.setData({
                            isLastPage: true
                        });
                        swan.showToast({
                            title: '没有更多内容',
                            mask: false,
                            duration: 1500
                        });
                    }
                    else {
                        swan.showToast({
                            title: response.data.message,
                            duration: 1500
                        })
                    }
                }
            })
            .catch(function (response) {
                if (data.page == 1) {
                    self.setData({
                        showerror: "block",
                        floatDisplay: "none"
                    });

                }
                else {
                    console.log(response);
                    swan.showModal({
                        title: '加载失败',
                        content: '加载数据失败,请重试.',
                        showCancel: false,
                    });
                    self.setData({
                        page: data.page - 1
                    });
                }
            })
            .finally(function (response) {
                swan.hideLoading();
                swan.stopPullDownRefresh();
            });
    },

    //加载分页
    loadMore: function (e) {

        var self = this;
        if (!self.data.isLastPage) {
            self.setData({
                page: self.data.page + 1
            });
            //console.log('当前页' + self.data.page);
            this.fetchPostsData(self.data);
        }
        else {
            swan.showToast({
                title: '没有更多内容',
                mask: false,
                duration: 1000
            });
        }
    },
    // 跳转至查看文章详情
    redictDetail: function (e) {
        // console.log('查看文章');
        var id = e.currentTarget.id,
            url = '../detail/detail?id=' + id;
        swan.navigateTo({
            url: url
        })
    },
    //首页图标跳转
    onNavRedirect: function (e) {
        var redicttype = e.currentTarget.dataset.redicttype;
        var url = e.currentTarget.dataset.url == null ? '' : e.currentTarget.dataset.url;
        var appid = e.currentTarget.dataset.appid == null ? '' : e.currentTarget.dataset.appid;
        var extraData = e.currentTarget.dataset.extraData == null ? '' : e.currentTarget.dataset.extraData;
        if (redicttype == 'apppage') {//跳转到小程序内部页面         
            swan.navigateTo({
                url: url
            })
        }
        else if (redicttype == 'webpage')//跳转到web-view内嵌的页面
        {
            url = '../webpage/webpage?url=' + url;
            swan.navigateTo({
                url: url
            })
        }
        else if (redicttype == 'miniapp')//跳转到其他app
        {
            swan.navigateToMiniProgram({
                appId: appid,
                envVersion: 'release',
                path: url,
                extraData: extraData,
                success(res) {
                    // 打开成功
                },
                fail: function (res) {
                    console.log(res);
                }
            })
        }

    },
    // 跳转至查看小程序列表页面或文章详情页
    redictAppDetail: function (e) {
        console.log('查看文章');
        var id = e.currentTarget.id;
        var redicttype = e.currentTarget.dataset.redicttype;
        var url = e.currentTarget.dataset.url == null ? '' : e.currentTarget.dataset.url;
        var appid = e.currentTarget.dataset.appid == null ? '' : e.currentTarget.dataset.appid;

        if (redicttype == 'detailpage')//跳转到内容页
        {
            url = '../detail/detail?id=' + id;
            swan.navigateTo({
                url: url
            })
        }
        if (redicttype == 'apppage') {//跳转到小程序内部页面         
            swan.navigateTo({
                url: url
            })
        }
        else if (redicttype == 'webpage')//跳转到web-view内嵌的页面
        {
            url = '../webpage/webpage?url=' + url;
            swan.navigateTo({
                url: url
            })
        }
        else if (redicttype == 'miniapp')//跳转到其他app
        {
            swan.navigateToMiniProgram({
                appId: appid,
                envVersion: 'release',
                path: url,
                success(res) {
                    // 打开成功
                },
                fail: function (res) {
                    console.log(res);
                }
            })
        }
    },
    scroll: function () {

        let marginTop = this.data.animStyle['margin-top'] - this.data.moveDistance
        // console.log(marginTop)

        this.setData({
            animStyle: {
                transition: 'all 0.5s',
                'margin-top': marginTop
            }
        });
        //   console.log(this.data.copyList)
        setTimeout(() => {
            this.setData({
                scrollList: this.data.scrollList.concat(this.data.copyList[this.data.index])
            })
            if (this.data.index == this.data.listLenght - 1) {
                this.setData({
                    scrollList: this.data.copyList,
                    index: 0,
                    animStyle: {
                        transition: 'all 0.5s',
                        'margin-top': 0
                    }
                })
            } else {
                this.setData({
                    index: this.data.index + 1,
                    peoples: this.data.peoples + 1 > 197 ? 197 : this.data.peoples + 1
                })
            }

        }, 1000)
    }
})
